/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package systole.view.workers;

import javax.swing.SwingWorker;
import org.jfree.chart.ChartPanel;
import systole.domain.signals.RawSignal;
import systole.domain.signals.Segment;
import systole.ioHandling.logs.SystoleLogger;
import systole.processor.filters.FilterProcessor;
import systole.processor.filters.FilterSettings;
import systole.view.charts.XYChart;
import systole.view.tabs.controllers.AnalysisController;

/**
 *
 * @author jmj
 */
public class WorkerFilter extends SwingWorker<Void, Void> {

    private XYChart filteredSignalModel;
    private ChartPanel rawSignalChart;
    private ChartPanel filteredSignalChart;
    private Segment segment;
    private AnalysisController parentControl;

    /**
     * @param analysisController
     */
    public WorkerFilter(AnalysisController analysisController) {
        super();
        this.parentControl = analysisController;
    }

    @Override
    protected Void doInBackground() {
        try {
            FilterSettings filtSet = new FilterSettings();
            filtSet.createDefault(this.parentControl.getAnalysis().getSignalFrequency().getFrequency().doubleValue());
            RawSignal rawSignal = this.parentControl.getAnalysis().getRawSignal();

            // primer grafico -> señal cruda
            XYChart rawSignalXYChart = new XYChart("Señal Original", "Muestras", "Amplitud (%)");
            rawSignalXYChart.setShowLegend(false);
            rawSignalXYChart.addSeries("Tren de Pulsos", rawSignal.getSegment().toDoubleArray(), 1);
            this.rawSignalChart = rawSignalXYChart.plot();

            this.segment = FilterProcessor.filterPulseWave(rawSignal.getSegment(), filtSet);

            // Si fue tomada invertida, la invierto
            if (rawSignal.isInverted()) {
                this.segment = this.segment.invert();
            }

            // segundo grafico -> señal invertida y filtrada
            this.filteredSignalModel = new XYChart("Señal Filtrada", "Muestras", "Amplitud (%)");
            filteredSignalModel.setShowLegend(false);
            this.filteredSignalModel.addSeries("Tren de Pulsos", this.segment.toDoubleArray(), 1);
            this.filteredSignalChart = this.filteredSignalModel.plot();
        } catch (Exception e) {
            SystoleLogger.getInstance().logError(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void done() {
        this.parentControl.getAnalysis().setSignalFiltered(this.segment);
        this.parentControl.getFrmAnalysis().addFilteredCharts(this.rawSignalChart, this.filteredSignalChart, this.filteredSignalModel);

        //Llamado al segmentado
        this.parentControl.startSlicing();
        this.filteredSignalModel = null;
        this.rawSignalChart = null;
        this.filteredSignalChart = null;
        this.segment = null;
    }
}
